package com.example.question.dp.dp5;

import java.util.HashMap;
import java.util.Map;

public class Code02_413 {
    public static void main(String[] args) {
        Code02_413 code = new Code02_413();
//        int count = code.numberOfArithmeticSlices(new int[]{1, 2, 3, 8, 9, 10});
        int count = code.numberOfArithmeticSlices(new int[]{1, 2, 3, 4});
        System.out.println(count);
    }

    public int numberOfArithmeticSlices1(int[] nums) {
        int m = nums.length;
        if (m < 3) {
            return 0;
        }
        boolean[][] dp = new boolean[m][m];
        int count = 0;
        for (int row = 0; row < m; row++) {
            for (int col = row + 2; col < m; col++) {
                // 这只是最后的三个数  是等差数列
                if (nums[col] - nums[col - 1] == nums[col - 1] - nums[col - 2]) {
                    // dp[row][col - 1] 也是 且和最后三个数的公差相等 dp[row][col] 才是true
                    if (dp[row][col - 1] && nums[row + 1] - nums[row] == nums[col] - nums[col - 1]) {
                        dp[row][col] = true;
                        count++;
                    }
                    if (!dp[col - 2][col]) {
                        dp[col - 2][col] = true;
                        count++;
                    }
                }
            }
        }
        return count;
    }

    public int numberOfArithmeticSlices(int[] nums) {
        int m = nums.length;
        if (m < 3) {
            return 0;
        }
        int[] differences = new int[nums.length - 1];
        for (int i = 1; i < nums.length; i++) {
            differences[i - 1] = nums[i] - nums[i - 1];
        }
        int diff = differences[0];
        int diffCount = 1;
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 1; i < differences.length; i++) {
            if (differences[i] == diff) {
                diffCount++;
            } else {
                if (diffCount >= 2) {
                    count += get(diffCount + 1, map);
                }
                diffCount = 1;
                diff = differences[i];

            }
        }
        // 最后一次的
        if (diffCount >= 2) {
            count += get(diffCount + 1, map);
        }
        return count;
    }

    private Integer get(Integer length, Map<Integer, Integer> map) {
        if (map.containsKey(length)) {
            return map.get(length);
        }
        int sum = 0;
        for (int i = 1; i <= length - 2; i++) {
            sum += i;
        }
        map.put(length, sum);
        return sum;
    }
}